/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/** 
 * $Id: MaCI_Text.cpp,v 1.1 2009-07-20 15:21:08 morsko Exp $
 *
 * \file
 * \brief Gimbo component for accessing MaCI Text
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"
#include "MaCI_Text_MaCITextFrame.h"
#include "wx/wx.h"

// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************

// Set initial verbosity level to 1
static int verbose = 1;
//*****************************************************************************
// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

// GIMnet parameters
static std::string gimnetAP = "asrobo.hut.fi";
static int gimnetAPPort = 50002;
static int gimboID;
static int reportID=-1;
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}

//*****************************************************************************

static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tCMaCIAlarmComponent [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-g name]\t\t\tThe gimnet id of the Gimbo instance this component is created by\n");
  fprintf(stderr,"  [-i id]\t\t\tComponent's report id used when reporting to Gimbo");
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

class MainApp : public wxApp
{
  public:
    virtual bool OnInit();
    
  private:
    MaCI_Text_MaCITextFrame *iMainFrame;
};


IMPLEMENT_APP(MainApp)


bool MainApp::OnInit()
{
  
  
  // setup signal handling
  InitSignalHandler();
  
  // Objects
  gimi::GIMI *g = new gimi::GIMI;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(4);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
          "\nMaCI_Text component for gimbo\n");
  
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "g:u:p:i:hqv");
    switch(c) {
      
      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// GIMnet parameters ////
      /////////////////////////////////

    case 'g':
      gimboID = atoi(optarg);
      dPrint(3,"Gimbo instance is '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'i':
      reportID = atoi(optarg);
      dPrint(3,"Using Report id '%d'", reportID);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
        debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g->connectToHubEx(gimnetAP, gimnetAPPort) ) != GIMI_OK) {
    dPrint(ODERROR,"Failed to connect to GIMnet AccessPoint '%s:%d': '%s'",
           gimnetAP.c_str(), 
           gimnetAPPort, 
           gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(ODINFO,"Succesfully connected to GIMnet at AccessPoint '%s:%d': '%s'",
           gimnetAP.c_str(), 
           gimnetAPPort,
           gimi::getGimiErrorString(r).c_str());
  
    //create frame
    iMainFrame = new MaCI_Text_MaCITextFrame(NULL);
    iMainFrame->Initialize(g, gimboID, reportID);
    iMainFrame->Show(true);
    
    r = TRUE;
  }
  
  return r;
}
